import React from 'react';
import BreadCrumb from '@/components/BreadCrumb';
import Basic from './Basic';
import Monitor from './Monitor';
import Advanced from './Advanced';
import s from './style.module.css';
import moment from 'moment'
import { Tabs, Button, Message ,Loading, Confirm } from '@knownsec/react-component';
import { useLocation, useHistory } from 'react-router-dom';
import { defaultData,defaultCheck } from './defaultData.js';
import { GetQueryString } from '@/common/constant';
import { getTargetInfo, getGroupInfo, targetAdd, putTarget, putGroup,productInfo } from '~/API';
import {WARNING_SECURITYEVENT_MAP2} from '@/common/common'
import { deepClone } from '@/utils';
const { TabPane } = Tabs;
const panes = [
  {
    title: '基本信息',
    content: Basic,
  },
  {
    title: '监测配置',
    content: Monitor,
  },
  {
    title: '高级扫描配置',
    content: Advanced,
  },
];
/**
 * 提交三种模式：修改Solo，修改Group，新增组
 * 获取两种模式：solo，group
 */
function FormPage() {
  const history = useHistory();
  const AdvancedForm = React.createRef();
  const dfData = deepClone(defaultData);
  const search = useLocation().search;
  const params = {
    data: { id: GetQueryString(search, 'id') },
    type: GetQueryString(search, 'type'),
    back: GetQueryString(search, 'back'),
  };
  const [formData, setFormData] = React.useState(dfData);
  const [linkArr, setLinkArr] = React.useState([]);
  const [sysinfo, setSysinfo] = React.useState([]);//下层禁用判断
  const [loading, setLoading] = React.useState(true);
  const product=JSON.parse(localStorage.product)
  const info=JSON.parse(localStorage.info||'{}')
  const getInfo = async () => {
    setLoading(true)
    const modules=info.modules||null
    let accept=deepClone(defaultData);;
    if (params.type === 'solo') {
      setLinkArr([
        { link: {
            pathname: '/monitor',
            search: `filter=${encodeURI(params.back)}`,
          }, name: '监测列表' },
        { link: '', name: '编辑', active: true },
      ]);
      const solo = await getTargetInfo(params.data.id);
      if (solo.status === 'success') {
        solo.data.target_urls = [solo.data.target_url];
        accept=solo.data;
      }
    } else if (params.type === 'group') {
      setLinkArr([
        { link: '', name: '任务管理' },
        { link: {
            pathname: '/task_group',
            search: `filter=${encodeURI(params.back)}`,
          }, name: '任务组' },
        { link: '', name: '编辑', active: true },
      ]);
      const res = await getGroupInfo(params.data.id);
      if (res.status === 'success') {
        accept=res.data;
      }
    } else if (params.type === 'groupadd') {
      setLinkArr([
        { link: '', name: '任务管理' },
        { link: {
            pathname: '/task_group',
            search: `filter=${encodeURI(params.back)}`,
          }, name: '任务组' },
        { link: '', name: '接入业务系统', active: true },
      ]);
    } else {
      setLinkArr([
        { link: {
            pathname: '/monitor',
            search: `filter=${encodeURI(params.back)}`,
          }, name: '监测列表' },
        { link: '', name: '接入业务系统', active: true },
      ]);
    }
      //证书控制表单项
    if(modules){
        const include_plugins=[]
        const acceptP= accept.job_config_map.securityEvent.include_plugins
        const plugins=[
            'black_links',
            'cryptojacking',
            'malscan',
            'privacy_disclosure',
            'keyword',
          ]
        plugins.forEach((e)=>{
            if(modules.includes(e)&&acceptP.includes(e)){
                include_plugins.push(e);
            }
        })
        setSysinfo(info.modules)
       !modules.includes('cloud')&&(accept.job_config_map.availability.use_cloud= modules.includes('cloud'))
        accept.job_config_map.securityEvent.include_plugins=include_plugins
    }
    setFormData(accept);
    setLoading(false)
  };
  const onsub = async () => {
    const message=(message,type='warning')=>{
      return Message.show({
        pro: true,
        showClose: false,
        message,
        type,
      })
    }
    if(product.status==='is_expired'&&product.is_trial){
      return  message('试用证书已过期，请重新上传证书。');
    }
    const checkArr=['vul','securityEvent','availability','risk_link','change_check']
    // 基础配置监测项验证
    if (params.type !== 'solo') {
      if (formData.task_config?.is_periodic) {
        let flag = false;
        checkArr.forEach((t) => {
          if (!formData.task_config[t].is_disabled && !formData.task_config[t].seconds) {
            flag = true;
          } else if (formData.task_config[t].is_disabled && !formData.task_config[t].seconds) {
            formData.task_config[t].seconds = formData.task_config[t].seconds || null;
          }
        });
        if (flag) {
          return  message('选中监测项的时间为必填');
        }
      } else {
        checkArr.forEach((t) => {
          formData.task_config[t].seconds = formData.task_config[t].seconds || null;
        });
      }
    }
    
    // 监测配置验证
    const is_periodic=formData.task_config.is_periodic
    //单次篡改关闭
    !is_periodic &&(formData.task_config.change_check.is_disabled=true)
    if (
      formData.job_config_map.securityEvent.crawler_scope == 3 &&
      !formData.job_config_map.securityEvent.include_url
    ) {
      return  message('请正确输入监测配置项');
    }
    // 周期验证证书频率
    if(is_periodic){
      for (const item of checkArr) {
        let infoSeconds=info[item]?info[item].seconds:''
        try {
          // 证书字段转换
          const validJsonString =info[item].replace(/'/g, '"');
          infoSeconds=JSON.parse(validJsonString).seconds
        } catch (error) {}
        // 证书控制 > 默认控制
        infoSeconds=infoSeconds||defaultCheck[item]
        const taskConfigItem=formData.task_config[item]
        if(!taskConfigItem.is_disabled && taskConfigItem.seconds<infoSeconds){
          return  message(`${WARNING_SECURITYEVENT_MAP2[item]}超出周期限制频率`);
          break;
        }
      }
    }
    if(!formData.task_config.vul.is_disabled&&!formData.job_config_map.vul.scan_profiles[0]){
      return  message('请选择漏洞模版');
    }
    // 高级扫描配置验证
    if (AdvancedForm.current) {
      const needValid = [];
      const ac = formData.advance_config;
      // 添加需要验证的表单
      if(ac.site_login){
          if(ac.login_method===0){
            needValid.push('login_form_action_url', 'login_form_postdata')
          }else if(ac.login_method===1){
            needValid.push('login_json_action_url', 'login_json_postdata')
          }else if(ac.login_method===2){
            needValid.push('request_cookie')
          }else if(ac.login_method===3){
            needValid.push('request_http_headers')
          }
      }
      ac.is_http_auth_enabled ? needValid.push('http_auth_username', 'http_auth_password') : null;
      ac.is_proxy_enabled
        ? ac.is_proxy_need_auth
          ? needValid.push(
              'proxy_scheme',
              'proxy_host',
              'proxy_port',
              'proxy_username',
              'proxy_password'
            )
          : needValid.push('proxy_scheme', 'proxy_host', 'proxy_port')
        : null;
      try {
        const values = await AdvancedForm.current.validateFields(needValid);
      } catch (errorInfo) {
      return  message('请正确输入高级扫描配置项');
      }
    }
      // 解决CM-2935，从高级扫描配置切换到基础页面后,下面两个urls为字符串 要切换为数组
      const excluded=formData.advance_config.crawler_excluded_urls 
      const included=formData.advance_config.crawler_included_urls 
      typeof excluded==='string'&& (formData.advance_config.crawler_excluded_urls=excluded?excluded.split('\n'):[])
      typeof included==='string'&&(formData.advance_config.crawler_included_urls=included?included.split('\n'):[])
    let res = null;
    const onOffArr = [
        'site_login',
        'is_http_auth_enabled',
        'is_proxy_enabled',
        'is_proxy_need_auth',
        'is_solo',
    ];
    onOffArr.forEach((e) => {
        formData.advance_config[e] = Boolean( formData.advance_config[e]);
    });
    const v = ['concurrency', 'is_filter_by_query_key', 'request_timeout', 'requests_per_sec']
    const advance_obj = formData.advance_config
    const obj = Object.keys(advance_obj).reduce((prev, cur) => {
        if (v.includes(cur)) {
          if (Array.isArray(advance_obj[cur])) {
            if (advance_obj[cur].length) {
              if (advance_obj[cur][0] !== 'true' && advance_obj[cur][0] !== 'false') {
                prev[cur] = advance_obj[cur][0]
              } else {
                prev[cur] = advance_obj[cur][0] === 'true' ? true : false
              }
            }
          } else {
            prev[cur] = advance_obj[cur]
          }
        } else {
          prev[cur] = advance_obj[cur]
        }
        return prev
    }, {})
    formData.advance_config = obj
    const { scan_period_end_time, scan_period_start_time } = formData.task_config
    if (scan_period_end_time && scan_period_start_time) {
      let diffM = moment(scan_period_end_time, 'HH:mm:ss').diff(moment(scan_period_start_time, 'HH:mm:ss'), 'minutes')
      diffM = diffM < 0 ? diffM + (24 * 60) : diffM
      if (diffM > (18 * 60) || diffM < (6 * 60)) {
        return false
      }
      Confirm({
        className: s.w460,
        title: '提示',
        message: <div className="confirmbox">周期任务将在您设置的每天监测时间段内进行，若该时间段内需监测的其他任务组过多，可能会导致部分任务组无法执行。</div>,
        onconfirm: submit,
        oncancel: () => {},
      })
      return false
    }
    submit()
    async function submit () {
      setLoading(true)
      if (params.type === 'solo') {
        res = await putTarget({ id: params.data.id, data: formData }).catch((err) => {
          return err;
        });
      } else if (params.type === 'group') {
        res = await putGroup({ id: params.data.id, data: formData }).catch((err) => {
          return err;
        });
      } else {
        res = await targetAdd(formData).catch((err) => {
          return err;
        });
      }
      setLoading(false)
      if (!res) {
        return;
      }
      if (res.status === 'success') {
        message('保存成功','success')
        const urls = linkArr[linkArr.length - 2].link;
        history.push(urls);
      } else {
          const json= {
              target_group_name:'任务组名称',
              target_urls:'监测业务系统',
            }
        const msg = Object.entries(res.data)[0];
        const errmsg_=(json[msg[0]]+':'+msg[1]).replace('undefined:','')
        message(errmsg_,'error')
      }
    }
  };
  const onChangeForm = (type, e) => {
    let formData_ = formData;
    if (type) {
      formData_[type] = Object.assign(formData_[type], e);
    } else {
      formData_ = Object.assign(formData_, e);
    }
    setFormData(formData_);
  };
  React.useMemo(() => {
    getInfo();
  }, [params.type]);

  return (
    <>
      <BreadCrumb arr={linkArr} />
      <div className={s.formBox}>
        <div className={s.form}>
        <Loading show={loading} label="" />
          <Tabs type="card" animated destroyInactiveTabPane={true}>
            {panes.map((e, i) => {
              const Addition = e.content;
              return (
                <TabPane tab={e.title} key={i}>
                  <Addition
                    formData={formData}
                    sysinfo={sysinfo}
                    formRef={AdvancedForm}
                    params={params}
                    onChange={onChangeForm}
                  />
                </TabPane>
              );
            })}
          </Tabs>
        </div>
        <div className={s.btnBox}>
          <div className={s.btn}>
            <Button pro type="primary" onClick={onsub}>
              保存
            </Button>
          </div>
        </div>
      </div>
    </>
  );
}

export default FormPage;
